<template>
  <view>
    <!-- #ifndef  H5 -->
    <u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
      <u-navbar
          :is-back="true"
          :title-bold="true"
          :is-fixed="false"
          title="确认订单"
          title-color="#000000"
          :border-bottom="false"
          back-icon-name="arrow-leftward"
          back-icon-color="#000000"
          :background="{ background: 'rgba(255,255, 255,0)' }"
      ></u-navbar>
    </u-sticky>
    <!-- #endif -->
    <view class="confirm-order">
      <view class="confirm-con">
        <view class="goods contain">
          <order-goods
              :team="{ need: orderInfo.team_need }"
              :list="goodsLists"
              :delivery="delivery"
              :order_type="orderInfo.order_type"
              mode="comfirm"
          ></order-goods>
        </view>
        <!-- 收货方式 -->
        <view class="contain">
          <view class="receiving-card">
            <u-image
                class="goods-icon-md mr10"
                width="28"
                height="26"
                src="/static/images/form_icon.png"
                mode="scaleToFill"
            />
            <view class="receiving-content">
              填写资料
            </view>
          </view>
          <!-- 门店自提表单 -->
          <view
              class="contain store-from"
          >
            <view class="store-from-item">
              <text>企业名称:</text>
              <u-input
                  v-model="companyName"
                  class="flex1"
                  type="text"

                  :clearable="false"
                  placeholder="请输入企业名称"
                  @blur="validateCompanyName"
              />
            </view>
            <view v-if="errors.companyName" class="error-text">{{ errors.companyName }}</view>

            <view class="store-from-item">
              <text>注册地址:</text>
              <u-input
                  v-model="companyAddress"
                  class="flex1"
                  type="text"
                  :clearable="false"
                  placeholder="请输入注册地址"
                  @blur="validateCompanyAddress"
              />
            </view>
            <view v-if="errors.companyAddress" class="error-text">{{ errors.companyAddress }}</view>

            <view class="store-from-item">
              <text>联系人:</text>
              <u-input
                  v-model="companyContact"
                  class="flex1"
                  type="text"
                  :clearable="false"
                  placeholder="请输入联系人"
                  @blur="validateCompanyContact"
              />
            </view>
            <view v-if="errors.companyContact" class="error-text">{{ errors.companyContact }}</view>

            <view class="store-from-item">
              <text>手机号:</text>
              <u-input
                  v-model="companyMobile"
                  class="flex1"
                  type="text"
                  :clearable="false"
                  placeholder="请输入联系方式"
                  @blur="validateCompanyMobile"
              />
            </view>
            <view v-if="errors.companyMobile" class="error-text">{{ errors.companyMobile }}</view>
            <uploader
                preview-size="180rpx"
                :mutiple="true"
                :maxUpload="5"
                :file-list="fileList"
                @after-read="afterRead"
                :deletable="true"
                @delete="deleteImage"
                image-fit="aspectFill"
            />
          </view>
          <!-- 快递配送 -->

        </view>
        <view class="contain">
          <view
              v-show="isExpressDelivery"
              class="receiving-card bg-white card-address"
              @click="onAddressExpress"
          >

            <view class="receiving-content receiving-content-gradient">
              <view v-if="address.id">
                <view class="black row-flex-start">
                  <u-image
                      class="location-icon mr10"
                      width="24"
                      height="30"
                      src="/static/images/icon_address.png"
                      mode="scaleToFill"
                  />
                  <text class="md">{{
                      address.province + ' ' +
                      address.city + ' ' +
                      address.district

                    }}
                  </text>
                </view>
                <view class="black xl mt5">
                  {{ address.address }}
                </view>
                <view class="xs black bold mt5">
                  <text>{{ address.contact }}</text>
                  <text class="ml10">{{ address.telephone }}</text>
                </view>
              </view>
              <view v-else>
                <view>请选择收货地址</view>
              </view>
            </view>
            <u-icon name="arrow-right" color="#8a8a8a"/>
          </view>
        </view>
        <view class="price contain">
          <view class="item row-between">
            <view>办理金额</view>
            <view>¥{{ orderInfo.total_goods_price }}</view>
          </view>
          <view class="item row-between">
            <view>平台服务费</view>
            <view>¥{{ orderInfo.goods_lists[0].stock }}</view>
          </view>
        </view>
      </view>
      <view class="footer bg-white row-between fixed">
        <view class="all-price lg row">
          <text>合计：</text>
          <view class="primary">
            <price-format
                :first-size="36"
                :second-size="20"
                :weight="700"
                color="#fa4000"
                :price="orderInfo.order_amount"
            ></price-format>
          </view>
        </view>
        <button class="btn br60 white" size="md" hover-class="none" @tap="onSubmitOrder">
          提交订单
        </button>
      </view>
    </view>
    <loading-view v-if="showLoading" background-color="transparent" :size="50"></loading-view>
    <loading-view v-if="isFirstLoading"></loading-view>
  </view>
</template>
<script>
import {orderBuy, getOrderCoupon, getDelivery} from '@/api/order'
import {teamBuy} from '@/api/activity'
import {prepay, getMnpNotice, getPayway} from '@/api/app'
import {wxpay, alipay} from '@/utils/pay'
import { uploadFile } from '@/utils/tools.js'
export default {
  data() {
    return {
      fileList: [],
      isFirstLoading: true,
      showLoading: false,
      address: {},
      orderInfo: {},
      goodsLists: [],
      addressId: '',
      useIntegral: 0,
      userRemark: '',
      userConsignee: '',
      userMobile: '',
      storeInfo: {},
      couponId: '',
      showCoupon: false,
      couponTabsIndex: 0,
      usableCoupon: [],
      unusableCoupon: [],
      bargainLaunchId: -1,
      addressTabsIndex: 0,
      companyContact:  '',
      companyName: '',
      companyMobile: '',
      companyAddress: '',
      addressTabsList: [
        {
          id: 1,
          sign: 'express',
          name: '快递配送'
        },
        {
          id: 2,
          sign: 'store',
          name: '门店自提'
        }
      ],
      errors: {
        companyName: '',
        companyAddress: '',
        companyContact: '',
        companyMobile: ''
      }
    }
  },

  computed: {
    delivery() {
      return this.addressTabsList[this.addressTabsIndex]['id']
    },
    isExpressDelivery() {
      return this.addressTabsList[this.addressTabsIndex]['sign'] === 'express'
    }
  },

  onLoad(options) {
    try {
      const data = JSON.parse(decodeURIComponent(options.data))
      this.goods = data.goods
      this.type = data.type
      this.teamId = data.teamId
      this.bargainLaunchId = options.bargain_launch_id
      this.foundId = data.foundId || 0
    } catch (e) {
      console.error('Invalid data parameter')
      return
    }

    getDelivery()
        .then(({code, data, msg}) => {
          if (code != 1) throw new Error(msg)
          return data
        })
        .then((data) => {
          if (!data.is_express) {
            this.addressTabsList = this.addressTabsList.filter(
                (item) => item.sign !== 'express'
            )
          }
          if (!data.is_selffetch) {
            this.addressTabsList = this.addressTabsList.filter(
                (item) => item.sign !== 'store'
            )
          }
        })
        .then(() => {
          this.handleOrderMethods('info')
          this.initCouponData()
        })
        .then(() => {
          uni.$on('selectaddress', (params) => {
            this.addressId = params.id
            this.handleOrderMethods('info')
          })

          uni.$on('payment', (params) => {
            setTimeout(() => {
              uni.$off('payment')

              if (params.result) {
                uni.redirectTo({
                  url: `/pages/pay_result/pay_result?id=${params.order_id}`
                })
              } else {
                uni.redirectTo({
                  url: '/pages/user_order/user_order'
                })
              }
            }, 500)
          })

          uni.$on('store', (params) => {
            this.storeInfo = params
          })
        })
        .catch((err) => {
          console.log(err)
        })
  },

  onUnload() {
    uni.$off(['selectaddress', 'store', 'payment'])
  },

  methods: {
    // 验证企业名称
    validateCompanyName() {
      if (!this.companyName.trim()) {
        this.errors.companyName = '请输入企业名称';
        return false;
      }
      this.errors.companyName = '';
      return true;
    },

    // 验证注册地址
    validateCompanyAddress() {
      if (!this.companyAddress.trim()) {
        this.errors.companyAddress = '请输入注册地址';
        return false;
      }
      this.errors.companyAddress = '';
      return true;
    },

    // 验证联系人
    validateCompanyContact() {
      if (!this.companyContact.trim()) {
        this.errors.companyContact = '请输入联系人';
        return false;
      }
      this.errors.companyContact = '';
      return true;
    },

    // 验证手机号
    validateCompanyMobile() {
      if (!this.companyMobile.trim()) {
        this.errors.companyMobile = '请输入手机号';
        return false;
      }
      const mobileReg = /^1[3-9]\d{9}$/;
      if (!mobileReg.test(this.companyMobile)) {
        this.errors.companyMobile = '手机号格式不正确';
        return false;
      }
      this.errors.companyMobile = '';
      return true;
    },

    // 验证所有字段
    validateAllFields() {
      const nameValid = this.validateCompanyName();
      const addressValid = this.validateCompanyAddress();
      const contactValid = this.validateCompanyContact();
      const mobileValid = this.validateCompanyMobile();

      return nameValid && addressValid && contactValid && mobileValid;
    },
    onAddressExpress() {
      uni.navigateTo({
        url: `/pages/user_address/user_address?type=${1}`
      })
    },
    authWechatMessage() {
      return new Promise((resolve, reject) => {
        getMnpNotice({
          scene: 1
        })
            .then(({code, data, msg}) => {
              if (code != 1) throw new Error(msg)
              return data
            })
            .then((data) => {
              if (!data.length) return reject()
              uni.requestSubscribeMessage({
                tmplIds: data,
                success(res) {
                  resolve(res)
                },
                fail(err) {
                  reject(err)
                }
              })
            })
            .catch((err) => {
              reject(err)
            })
      })
    },

    afterRead(e) {
      const file = e
      uni.showLoading({
        title: '正在上传中...',
        mask: true
      })
      file.map((item) => {
        uploadFile(item.path)
            .then((res) => {
              uni.hideLoading()
              this.fileList.push(res)
            })
            .catch(() => {
              uni.hideLoading()
              this.$toast({
                title: '上传失败'
              })
            })
      })
    },
    deleteImage(index) {
      this.fileList.splice(index, 1);
    },
    onSubmitOrder() {
      if (!this.validateAllFields()) {
        this.$toast({title: '请完善表单信息'})
        return
      }
      uni.showModal({
        title: '温馨提示',
        content: '是否确认下单?',
        confirmColor: '#FF2C3C',
        success: ({confirm}) => {
          if (!confirm) return

          // #ifdef MP-WEIXIN
          this.authWechatMessage()
              .catch((err) => {
                console.log(err)
              })
              .finally(() => {
                this.handleOrderMethods('submit')
              })
          // #endif

          // #ifndef MP-WEIXIN
          this.handleOrderMethods('submit')
          // #endif
        }
      })
    },

    initCouponData() {
      getOrderCoupon({
        goods: this.goods
      })
          .then(({code, data, msg}) => {
            if (code != 1) throw new Error(msg)
            return data
          })
          .then((data) => {
            this.usableCoupon = data.usable
            this.unusableCoupon = data.unusable
          })
          .catch((err) => {
            console.log(err)
          })
    },

    async initPageData(from) {
      this.showLoading = true

      try {
        const {code, data, msg} = this.teamId ? await teamBuy(from) : await orderBuy(from)

        if (code == 1) {
          this.address = data.address
          this.goodsLists = data.goods_lists
          if (data.selffetch_info) {
            this.storeInfo = data.selffetch_info.selffetch_shop || {}
            this.userConsignee = data.selffetch_info.contact
            this.userMobile = data.selffetch_info.mobile
          }

          this.orderInfo = data
          this.$nextTick(() => {
            this.isFirstLoading = false
          })
        } else {
          throw new Error(msg)
        }
      } catch (err) {
        console.log(err)
        this.$toast({title: '网络异常，请重新进入页面'})
      } finally {
        this.showLoading = false
      }
    },

    async handleOrderSubmit(from) {
      this.showLoading = true

      from.remark = this.userRemark
      from.type = this.type

      try {
        const {code, data, msg} = this.teamId ? await teamBuy(from) : await orderBuy(from)

        if (code == 1) {
          uni.redirectTo({
            url: `/pages/payment/payment?from=${data.type}&order_id=${data.order_id}`
          })
        } else {
          throw new Error(msg)
        }
      } catch (err) {
        console.log(err)
        this.$toast({title: '下单异常，请重新操作'})
      } finally {
        this.showLoading = false
      }
    },

    buildOrderFrom(action) {
      const orderFrom = {
        action,
        goods: this.goods,
        delivery_type: this.delivery,
        use_integral: this.useIntegral,
        address_id: this.addressId,
        coupon_id: this.couponId,
        bargain_launch_id: this.bargainLaunchId == -1 ? '' : this.bargainLaunchId
      }

      if (this.addressTabsList[this.addressTabsIndex]['sign'] === 'store') {
        orderFrom.selffetch_shop_id = this.storeInfo.id
        orderFrom.consignee = this.userConsignee
        orderFrom.mobile = this.userMobile
      }
      let image = this.fileList.map((item) => item.base_url)
      orderFrom.companyContact = this.companyContact
      orderFrom.companyMobile = this.companyMobile
      orderFrom.companyAddress = this.companyAddress
      orderFrom.companyName = this.companyName
      orderFrom.companyImages = image

      if (this.teamId) {
        const goods = this.goods[0]
        delete orderFrom.goods
        orderFrom.item_id = goods.item_id
        orderFrom.goods_num = goods.num
        orderFrom.team_id = this.teamId
        orderFrom.found_id = this.foundId
      }

      return orderFrom
    },

    handleOrderMethods(action) {
      const orderFrom = this.buildOrderFrom(action)
      switch (action) {
        case 'info':
          this.initPageData(orderFrom)
          break
        case 'submit':
          this.handleOrderSubmit(orderFrom)
          break
      }
    }
  }
}
</script>
<style>
page {
  background-color: #f5f9ff;
}

.confirm-order .confirm-con {
  overflow: hidden;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.confirm-order {
  margin: 0 20rpx;
}

.confirm-order .contain {
  border-radius: 14rpx;
  margin: 20rpx 0;
  background-color: #fff;
  overflow: hidden;
}

.confirm-order .img-line {
  height: 1.5px;
  width: 100%;
  display: block;
}

.confirm-order .coupons {
  height: 100rpx;
  padding: 0 24rpx;
}

.goods .title {
  padding: 22rpx 24rpx;
  border-bottom: 1px solid #f6f6f6;
}

.goods .all-num {
  padding: 22rpx 24rpx;
  border-bottom: 1px dotted #f6f6f6;
}

.confirm-order .footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  padding: 0 30rpx;
  box-sizing: content-box;
  padding-bottom: env(safe-area-inset-bottom);
}

.confirm-order .price {
  padding: 28rpx 20rpx;
}

.confirm-order .price .item:not(:last-of-type) {
  margin-bottom: 20rpx;
}

.confirm-order .goods > .item,
.confirm-order .benefit > .item {
  padding: 0 24rpx;
  height: 80rpx;
}

.confirm-order .btn {
  background: #fa4000;
  padding: 0 50rpx;
}

.confirm-order .van-cell:after {
  border: none;
}

.goods .shop-icon {
  width: 40rpx;
  height: 40rpx;
}

.pop-title {
  height: 100rpx;
  border-bottom: 1rpx solid #f2f2f2;
}

.pop-title .title {
  margin-left: 30rpx;
  font-size: 34rpx;
  font-weight: bold;
  line-height: 36rpx;
}

.receiving-way {
  margin: 20rpx 20rpx 0 20rpx;
  border-radius: 7px;
  background-color: #ffffff;
  overflow: hidden;
}

.receiving-card {
  display: flex;
  align-items: center;
  padding: 20rpx;


}

.receiving-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  font-weight: bold;
}

.store-from {
  padding: 0 20rpx;
  font-size: 28rpx;
}

.store-from-item {
  display: flex;
  align-items: center;
  height: 100rpx;
}

.goods-icon-md {
  min-height: 30rpx;
  min-width: 30rpx;
  height: 38rpx;
  width: 28rpx;
  vertical-align: center;
}

.store-from-item text {
  width: 130rpx;
}

.location-icon {
  flex-shrink: 0;
}

.row-flex-start {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.receiving-content-gradient {
  background: linear-gradient(to right, #f5f7f8 20%, #ffffff 80%);
  padding:10rpx;
  border-radius: 16rpx;
}
.card-address {
  padding:10rpx;
}
.error-text {
  color: #ff4d4f;
  font-size: 24rpx;
  margin: 10rpx 20rpx;
  text-align: left;
}
</style>
